<?php

namespace app\api\model;

use think\Model;
use think\Db;
use EasyWeChat\Foundation\Application;


class Zzrecord extends Model
{

    //添加或修改记录信息
    public function addOrEdit()
    {
        $id = input('id');
        $tuijianp = input('tuijianp');
        $beituijianp = input('beituijianp');
        $openid = input('openid');
        
        //获取当前使用用户的信息，不知道对不对
        // $wechatApp = new \app\mpbase\library\WechatApp();
        // $info = $wechatApp->decryptData();
        $info = Db::name('user')->where('openid',$openid)->find();

        $data = Db::name('zzrecord')->where('id',$id)->find();
        $data['updatetime'] = time();
        // DB::startTrans();
        // try {    
            //发起人发起请求，添加记录
            if(empty($tuijianp)){
                //确认支付知否完成，完成才增加记录
                
                //支付签名
                // public function pay()
                // {
                //     $wechatApp = new \app\mpbase\library\WechatApp();
                //     $res = $wechatApp->pay();
                //     return json($res);
                // }

                // //支付回调
                // public function notify_redirect()
                // {
                //     $wechatApp = new \app\mpbase\library\WechatApp();
                //     $wechatApp->payNotify();
                // }

                
                
                
                //生成找人唯一码
                $code = Db::name('zzrecord')->order('id desc')->field('code')->find();
                $data['code'] = !empty($code['code'])?$code['code']:1000;
                $data['code'] = $data['code']+1;
                //接受商家发起请求的数据
                $data['company'] = input('company');
                $data['images'] = input('images');
                $data['content'] = input('content');
                $data['faqip'] = input('faqip');
                $ret = $this->isMobile(input('faqip'));
                if(!$ret){
                   return ['_code' => 500, 'msg' => '手机号码错误!']; 
                }
                $data['redpacket1'] = input('redpacket1');
                $data['faqi_avatar'] = $info['avatar'];
                $data['faqi_openid'] = $info['openid'];
                $data['nickname'] = $info['nickname'];
                //获取红包分配方案，进行分配
                $path = Db::name('zzpercent')->where('isuse',2)->find();
                $data['redpacket2'] = round($data['redpacket1'] * $path['tuijian'],1);
                $data['redpacket3'] = round($data['redpacket1'] * $path['beituijian'],1);
                $data['redpacket4'] = $data['redpacket1'] - $data['redpacket2'] -$data['redpacket3']; 

                
                
                $res = Db::name('zz_user')->where('openid','=',$info['openid'])->find();
                if(empty($res)){
                     Db::name('zz_user')->insert(['openid'=>$info['openid'],'phone'=>$data['faqip']]);
                }else{
                     Db::name('zz_user')->where('openid','=',$info['openid'])->setField(['phone'=>$data['faqip']]);
                }
                //往记录表添加信息
                $res = Zzrecord::allowField(true)->save($data);
                $id = Db::name('zzrecord')->getLastInsID();
                
                //生成二维码,$url为要跳转的页面，后面写死
                // $data['qrcode_1'] = $this->qrCode($id,$url);

            //推荐人推荐请求，更新记录
            }elseif(empty($beituijianp)){
                $ret = $this->isMobile($tuijianp);
                if(!$ret){
                   return ['_code' => 500, 'msg' => '手机号码错误!']; 
                }
                $res = Db::name('zz_user')->where('openid','=',$info['openid'])->find();
                if(empty($res)){
                     Db::name('zz_user')->insert(['phone'=>$tuijianp,'openid'=>$info['openid']]);
                }else{
                     Db::name('zz_user')->where('openid','=',$info['openid'])->setField(['phone'=>$tuijianp]);
                }


                //生成二维码,$url为要跳转的页面，后面写死
                // $data['qrcode_2'] = $this->qrCode($id,$url);


                //判断是否是第一个推荐的人
                $ret = Db::name('zzrecord')->where('id','=',$id)->field('tuijianp')->find();
                if(empty($ret['tuijianp'])){
                    //是第一个
                    $res = Db::name('zzrecord')->where('id',$id)->setField(['tuijianp'=>$tuijianp,'updatetime'=>$data['updatetime'],'qrcode_2'=>$data['qrcode_2'],'tuijian_avatar'=>'$info['avatar']','tuijian_openid'=>'$info['openid']']);
                }else{
                    //不是第一个
                    // $res = Db::name('zz_user')->where('phone','=',$tuijianp)->find();
                    // if(empty($res)){
                    //      Db::name('zz_user')->insert(['phone'=>$tuijianp]);
                    // }
                    $data['id'] = '';
                    $data['faqip'] = $data['faqip'];
                    $data['tuijianp'] = $tuijianp;
                    $data['tuijian_avatar'] = $info['avatar'];
                    $data['tuijian_openid'] = $info['openid'];
                    $data['nickname'] = $data['nickname'];
                    $res = Zzrecord::allowField(true)->save($data);
                    $id = Db::name('zzrecord')->getLastInsID();
                }
                
            //潜在客户提交数据，更新记录
            }else{
                $ret = $this->isMobile($beituijianp);
                if(!$ret){
                   return ['_code' => 500, 'msg' => '手机号码错误!']; 
                }
                $res = Db::name('zz_user')->where('openid','=',$info['openid'])->find();
                if(empty($res)){
                     Db::name('zz_user')->insert(['phone'=>$beituijianp,'openid'=>$info['openid']]);
                }else{
                     Db::name('zz_user')->where('openid','=',$info['openid'])->setField(['phone'=>$beituijianp]);
                }

                //判断是否是第一个被推荐的人
                $ret = Db::name('zzrecord')->where('id','=',$id)->find();
                if(empty($ret['beituijianp'])){
                    // 是第一个
                    $order_no = self::generateOrderCode();
                    $res = Db::name('zzrecord')->where('id',$id)->setField(['beituijianp'=>$beituijianp,'updatetime'=>$data['updatetime'],'order_no'=>$order_no,'beituijian_avatar'=>'$info['avatar']','beituijian_openid'=>'$info['openid']']);
                    //根据这个找人码code判断是否是第一个潜在客户，是返回payed=1，不是返回payed=2
                    $ret = Db::name('zzrecord')->where('code',$ret['code'])->count();
                    if($ret>1 && $res>0){
                        return ['_code' => 201, 'msg' => '保存成功','id' => $id,'payed'=>2];
                    }elseif($ret<=1 && $res>0){
                        return ['_code' => 201, 'msg' => '保存成功','id' => $id,'payed'=>1];
                    }else{
                        return ['_code' => 500, 'msg' => '保存失败!'];
                    }
                    
                }else{
                    //不是第一个
                    // $res = Db::name('zz_user')->where('phone','=',$beituijianp)->find();
                    // if(empty($res)){
                    //      Db::name('zz_user')->insert(['phone'=>$beituijianp]);
                    // }
                    $data['id'] = '';
                    $data['faqip'] = $data['faqip'];
                    $data['tuijianp'] = $tuijianp;
                    $data['beituijianp'] = $beituijianp;
                    $data['beituijian_avatar'] = $info['avatar'];
                    $data['beituijian_openid'] = $info['openid'];
                    $data['nickname'] = $data['nickname'];
                    $order_no = self::generateOrderCode();
                    $data['order_no'] = $order_no;
                    $res = Zzrecord::allowField(true)->save($data);
                    $id = Db::name('zzrecord')->getLastInsID();

                    if ($res > 0)
                        return ['_code' => 201, 'msg' => '保存成功','id' => $id,'payed'=>2];
                    else
                        return ['_code' => 500, 'msg' => '保存失败!'];
                                
                }

            }

        // Db::commit();
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     //throw $e;
        // }

        if ($res > 0)
            return ['_code' => 201, 'msg' => '保存成功','id' => $id];
        else
            return ['_code' => 500, 'msg' => '保存失败!'];
    }


    /*  生成订单编号*/
    public static function generateOrderCode()
    {
        date_default_timezone_set("PRC");
        $prefix = 'A' . chr(85 - date('m')) . chr(65 + date('d') % 26);
        $orderSn = $prefix . date('dd') . substr(time(), -4) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }



    public function message($userOpenId,$templateId,$url,$data)
    {

        $app = new Application($options);

        $notice = $app->notice;
        $messageId = $notice->to($userOpenId)->uses($templateId)->andUrl($url)->data($data)->send();
        return $messageId;
    }

        //验证是否是正确的手机号
    protected function isMobile($value)
    {
        $rule = '/^0?(13|14|15|17|18)[0-9]{9}$/';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

}